package cn.xuguowen.tool;

import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * ClassName: ExportWordUtil
 * Package: cn.xuguowen.tool
 * Description:
 * 借助freemarker模板引擎技术实现复杂word模板的导出
 *
 * @Author 徐国文
 * @Create 2023/4/1 17:01
 * @Version 1.0
 */
public class ExportWordUtil {

    public static final String SUFFIX = ".doc";


    // freemarker的配置类
    public static Configuration configuration;

    // 初始化配置类的信息
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding(Charset.defaultCharset().name());
        configuration.setClassForTemplateLoading(ExportWordUtil.class,"/template/word");
    }

    /**
     * 导出word文档
     * @param map           数据
     * @param title      文件名称
     * @param ftlName       模板名称
     */
    public static void exportWord(Map<String,Object> map,String title,String ftlName) {
        // 一个流两个头
        File file = null;
        InputStream is = null;
        ServletOutputStream out = null;

        try {
            // 1.借助模板在内存中生成一个临时的word文件
            Template template = configuration.getTemplate(ftlName);
            file = createDocFile(map,template);

            // 2.读取临时文件的内容
            is = new FileInputStream(file);
            String fileName = title + SUFFIX;
            HttpServletResponse response = SpringContextUtils.getHttpServletResponse();
            response.setCharacterEncoding(Charset.defaultCharset().name());
            // 两个头
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,Charset.defaultCharset().name()));

            // 一个流
            out = response.getOutputStream();

            // 3.从输入流中读取数据写入到输出流中out
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = is.read(buf)) != -1) {
                out.write(buf,0,len);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            // 注意：将内存中生成的临时文件删除掉
            file.deleteOnExit();
        }

    }

    /**
     * 在内存中根据模板生成一个word文件
     * @param dataMap       数据
     * @param template      模板对象
     * @return
     */
    private static File createDocFile(Map<String,Object> dataMap,Template template)  {
        // 默认在内存中生成的文档文件
        File file = new File("init.doc");
        Writer writer = null;
        try {
            // 1.向init.doc文件中写入数据
            writer = new OutputStreamWriter(new FileOutputStream(file),Charset.defaultCharset());
            template.process(dataMap,writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                // 2.关闭资源
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return file;
    }
}
